package com.change.study.data.dao.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.change.study.data.core.BaseDaoImpl;
import com.change.study.data.core.Finder;
import com.change.study.data.core.Pagination;
import com.change.study.data.dao.UserPointsDao;
import com.change.study.data.entity.User;
import com.change.study.data.entity.UserPoints;

@Repository
public class UserPointsDaoImpl extends BaseDaoImpl<UserPoints, Long> implements
		UserPointsDao {
	public Pagination getPage(int pageNo, int pageSize) {
		Criteria crit = createCriteria();
		Pagination page = findByCriteria(crit, pageNo, pageSize);
		return page;
	}

	public UserPoints findById(Long id) {
		UserPoints entity = get(id);
		return entity;
	}

	public UserPoints save(UserPoints bean) {
		getSession().save(bean);
		return bean;
	}

	public UserPoints deleteById(Long id) {
		UserPoints entity = super.get(id);
		if (entity != null) {
			getSession().delete(entity);
		}
		return entity;
	}

	@Override
	protected Class<UserPoints> getEntityClass() {
		return UserPoints.class;
	}

	@Autowired
	public void setSuperSessionFactory(SessionFactory sessionFactory) {
		super.setSessionFactory(sessionFactory);
	}

	@Override
	public UserPoints findByUserId(Long id) {
		UserPoints result = null;
		Finder finder = Finder
				.create("from UserPoints u where u.user.id=:userid");
		finder.setParam("userid", id);
		List<UserPoints> list = find(finder);
        if(list!=null&&list.size()>0){
        	result=list.get(0);
        }else{
        	result=new UserPoints();
        	User user=new User();
        	user.setId(id);
        	result.setUser(user);
        	result.init(user);
        	save(result);
        }
		return result;
	}
}